import { useState, useRef, useEffect, lazy, Suspense } from 'react'
import { Button, message } from 'antd'
import { useSelector } from 'react-redux'
import { PlusOutlined, DeleteOutlined, LockOutlined, UnlockOutlined, CopyOutlined, SendOutlined } from '@ant-design/icons'
import LdPrintTable from '../../../../components/LdPrintTable'
import bus from '../../../../utils/eventBus'
import { SET_APP_TYPE, files } from "./config";
import './index.scss'
const BarCodeView = lazy(() => import('./BarCodeView'))
interface pageType {
    total: number,
    pageSize: number,
    currentPage: number
}
const BarCodeManage = () => {
    const { enableClone = true, enablePrint = true } = useSelector((state: any) => state.licenseInfoReducer.licenseInfo)
    const [data, setData] = useState<any[]>([])
    const [drawer, setDrawer] = useState<boolean>(false)
    const detailRow = useRef<any>(null)
    const [multipleSelection, setMultipleSelection] = useState<any[]>([])
    const pageConfig = useRef<pageType>({
        total: 0,
        pageSize: 10,
        currentPage: 1
    })
    const columns = useRef([
        { key: 'name', dataIndex: "name", title: "策略名称", ellipsis: true },
        { key: 'keyLabel', dataIndex: 'keyLabel', title: '应用类型', width: 90 },
        {
            key: 'isRelease',
            dataIndex: "isRelease",
            title: '是否发布',
            width: 90,
            render: (_: any, record: any) => {
                return (
                    <span>{record.isRelease === 1 ? '是' : '否'}</span>
                )
            }
        },
        { key: "enableLabel", dataIndex: "enableLabel", title: '状态', width: 55 },
        { key: 'version', dataIndex: 'version', title: '版本', width: 55, },
        {
            key: 'action',
            dataIndex: 'action',
            title: '操作',
            width: 55,
            render: (_: any, record: any) => {
                return (
                    <Button type="link" style={{ fontSize: '14px', padding: 0 }} onClick={() => handleViewDetail(record)}>{record.isRelease === 1
                        ? "查看" : "设置"}</Button>
                )
            }
        }

    ])
    const handlePage = (data: pageType) => {
        pageConfig.current = { ...pageConfig.current, ...data }
        setGetCodeData()
    }
    const selectRowChange = (data: any[]) => {
        setMultipleSelection(data)
    }
    const releaseBceCodeStrategyFinished = (res: any) => {
        handleBack(res);
    }
    const handleRelease = () => {
        if (!multipleSelection.length)
            return message.warning("请先勾选策略，再执行操作！！！");
        if (multipleSelection.length > 1)
            return message.warning("仅支持一条一条策略执行操作！！！");
        const [data] = multipleSelection;
        const everyIsRelease = multipleSelection.every(item => item.isRelease === 0)
        if (!everyIsRelease) return message.warning('已经发布的策略不能再发布！！！')
        window.chromePro.releaseBceCodeStrategy(JSON.stringify({ id: data.id }));
        window.chromePro.releaseBceCodeStrategy(JSON.stringify({ id: data.id }));
    }
    const copyBceCodeStrategyFinished = (res: any) => {
        handleBack(res);
    }
    const handleCopy = () => {
        if (!multipleSelection.length) {
            message.warning("请先勾选策略，再执行操作！！！");
            return
        }
        if (multipleSelection.length > 1) {
            message.warning("仅支持一条一条策略执行操作！！！");
            return
        }
        const [data] = multipleSelection;
        window.chromePro.copyBceCodeStrategy(JSON.stringify(data));
    }
    const delBceCodeStrategyFinished = (res: any) => {
        handleBack(res);
    }
    const handleDel = () => {
        if (!multipleSelection.length) {
            message.warning("请先勾选策略，再执行操作！！！");
            return
        }
        if (multipleSelection.length > 1) {
            message.warning("仅支持一条一条策略执行操作！！！");
            return
        }
        const [data] = multipleSelection;
        if (data.isRelease === 1) {
            message.warning("该条策略已发布，不可删除！");
            return
        }
        const params = { id: data.id };
        window.chromePro.delBceCodeStrategy(JSON.stringify(params));
    }
    const enableBceCodeStrategyFinished = (res: any) => {
        handleBack(res);
    }
    const setGetCodeData = () => {
        const params = {
            type: 0,
            ...pageConfig.current,
        }
        if (enableClone && enablePrint) {
            params.type = 0
        } else if (enableClone) {
            params.type = 4
        } else if (enablePrint) {
            params.type = 1
        } else if (!enableClone && !enablePrint) {
            return
        }
        window.chromePro.getBceCodeStrategy(JSON.stringify(params));
    }
    const handleViewDetail = (data: any) => {
        //isRelease:0 未发布，1已发布
        const { isRelease = 0 } = data
        detailRow.current = { ...data, isRelease }
        setDrawer(true)
    }
    //获取数据回调
    const loadData = (data: any = {}) => {
        if (data.code === 200) {
            //处理适用文件数据格式
            data.data.map((item: any) => {
                let docTypeArr = item.docType.split(",");
                item.enableLabel = item.enable == 1 ? "启用" : "禁用";
                SET_APP_TYPE.map((v) => {
                    if (item.key === v.value) {
                        item.keyLabel = v.label;
                    }
                });
                item.docTypeLabel = files
                    .filter((item) => docTypeArr.find((v: any) => v === item.value))
                    .map((i) => i.name)
                    .join("、");
            });
            setData([...data.data])
            pageConfig.current = { ...pageConfig.current, total: data.total }
        } else {
            setData([])
            message.error(data.msg);
        }
    }
    const refresh = () => {
        pageConfig.current = { ...pageConfig.current, currentPage: 1 }
        setGetCodeData();
    }
    const handleEnable = (status: boolean) => {
        if (!multipleSelection.length) {
            message.warning("请先勾选策略，再执行操作！！！");
            return
        }
        if (multipleSelection.length > 1) {
            message.warning("仅支持一条一条策略执行操作！！！");
            return
        }
        const [data] = multipleSelection;
        if (data.enable === 1 && status)
            return message.warning("当前选择的策略已经是启用状态");
        if (data.enable === 0 && !status)
            return message.warning("当前选择的策略已经是禁用状态");
        const params = {
            id: data.id,
            enable: status ? 1 : 0,
        };
        window.chromePro.enableBceCodeStrategy(JSON.stringify(params));
    }
    //统一回调结果处理
    const handleBack = (res: any) => {
        if (res.code === 200) {
            message.success(res.msg);
            pageConfig.current = { ...pageConfig.current, currentPage: 1 }
            setGetCodeData();
            return;
        }
        message.error(res.msg);
    }
    const handleClose = () => {
        setDrawer(false)
    }
    useEffect(() => {
        setGetCodeData();
        bus.addListener("getBceCodeStrategyFinished", loadData);
        bus.addListener(
            "enableBceCodeStrategyFinished",
            enableBceCodeStrategyFinished
        );
        bus.addListener(
            "delBceCodeStrategyFinished",
            delBceCodeStrategyFinished
        );
        bus.addListener(
            "copyBceCodeStrategyFinished",
            copyBceCodeStrategyFinished
        );
        bus.addListener(
            "releaseBceCodeStrategyFinished",
            releaseBceCodeStrategyFinished
        );
    }, [])
    useEffect(() => {
        return () => {
            bus.removeListener("getBceCodeStrategyFinished", loadData);
            bus.removeListener(
                "enableBceCodeStrategyFinished",
                enableBceCodeStrategyFinished
            );
            bus.removeListener(
                "delBceCodeStrategyFinished",
                delBceCodeStrategyFinished
            );
            bus.removeListener(
                "copyBceCodeStrategyFinished",
                copyBceCodeStrategyFinished
            );
            bus.removeListener(
                "releaseBceCodeStrategyFinished",
                releaseBceCodeStrategyFinished
            );
        }
    }, [])
    return (
        <>
            <div className="policy-manage">
                <div className="action">
                    <Button icon={<PlusOutlined />} type="primary" onClick={() => handleViewDetail({})}>新增</Button>
                    <Button icon={<DeleteOutlined />} type="primary" danger onClick={handleDel}>删除</Button>
                    <Button icon={<SendOutlined />} type="dashed" onClick={handleRelease}>发布</Button>
                    <Button icon={<CopyOutlined />} type="dashed" onClick={handleCopy}>复制</Button>
                    <Button icon={<UnlockOutlined />} type="dashed" onClick={() => handleEnable(true)}>启用</Button>
                    <Button icon={<LockOutlined />} danger onClick={() => handleEnable(false)}>禁用</Button>
                </div>
                <div style={{ height: 'calc(100% - 42px)' }}>
                    <LdPrintTable
                        data={data}
                        columns={columns.current}
                        handlePage={handlePage}
                        pageConfig={pageConfig.current}
                        selectRowChange={selectRowChange}
                    >
                    </LdPrintTable>
                </div>
            </div>
            <Suspense>
                {
                    drawer ? <BarCodeView detailRow={detailRow.current} onClose={handleClose} refresh={refresh} /> : null
                }
            </Suspense>
        </>
    )
}
export default BarCodeManage